package com.dynamo.transport.network.practise.channel;

import org.jboss.netty.util.CharsetUtil;

import java.nio.ByteBuffer;

/**
 * @author duanyimiao
 * @create 2018-11-18 6:26 AM
 * @description
 **/
public class SimpleChannelUpstreamHandler implements ChannelUpstreamHandler {
    @Override
    public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) {
        System.out.println("SimpleChannelUpstreamHandler handleUpstream" + ctx.getHandler());

        if (e instanceof ChannelStateEvent) {
            ChannelStateEvent event = (ChannelStateEvent) e;
            if (event.getValue() == Channel.OPEND) {
                channelOpen(ctx, event);
            } else if (event.getValue() == Channel.CONNECTED) {
                channelConnected(ctx, event);
            }
        }
        if (e instanceof MessageEvent) {
            messageReceived(ctx, (MessageEvent) e);
        }

        ctx.sendUpstream(e);
    }

    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {

        ctx.sendUpstream(e);
    }

    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {

        ctx.sendUpstream(e);
        System.out.println("channel has already connect");
    }

    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {

        ByteBuffer buffer = ((ByteBuffer)e.getMsg());
        //转换成读模式
        buffer.flip();
        byte[] b = new byte[buffer.remaining()];
        buffer.get(b);
        System.out.println("size="+b.length+"  msg="+new String(b));

        e.getChannel().write("haha");

        ctx.sendUpstream(e);
    }
}
